package com.sub.framework.security.service;

import javax.annotation.Resource;

import com.sub.common.constant.UserConstants;
import com.sub.common.pojo.AppletLoginRest;
import com.sub.common.utils.JacksonUtils;
import com.sub.common.utils.SecurityUtils;
import com.sub.common.utils.http.HttpUtils;
import com.sub.framework.web.domain.AjaxResult;
import com.sub.project.system.domain.SysUser;
import com.sub.project.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.sub.common.constant.Constants;
import com.sub.common.exception.CustomException;
import com.sub.common.exception.user.CaptchaException;
import com.sub.common.exception.user.CaptchaExpireException;
import com.sub.common.exception.user.UserPasswordNotMatchException;
import com.sub.common.utils.MessageUtils;
import com.sub.framework.manager.AsyncManager;
import com.sub.framework.manager.factory.AsyncFactory;
import com.sub.framework.redis.RedisCache;
import com.sub.framework.security.LoginUser;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaException();
        }
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }
    @Autowired
    ISysUserService sysUserService;
    /**
     *   小程序登录
     * @param code 小程序code
      * @return
     */
    public AjaxResult appletLogin(String code, String url , String nickName){
        AjaxResult ajax = AjaxResult.success();
        String res = HttpUtils.sendGet(UserConstants.WX_LOGIN_URL,"appid="+UserConstants.APP_ID+"&secret="+UserConstants.APPSECRET+"&js_code="+code+"&grant_type=authorization_code");
      /** 获取小程序登录的对象*/
      AppletLoginRest appletLoginRest =  JacksonUtils.json2pojo(res, AppletLoginRest.class);
      /** 查询是否存在用户*/
       SysUser sysUser = sysUserService.selectUserByOpenId(appletLoginRest.getOpenid());
       if (sysUser == null){
           /** 新增小程序用户*/
           sysUser = new SysUser(appletLoginRest.getOpenid(),appletLoginRest.getSession_key(),url,nickName);
           sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
           sysUser.setOpenId(appletLoginRest.getOpenid());
           Long[] roleIds = {2l};
           sysUser.setRoleIds(roleIds);
           sysUserService.insertUser(sysUser);
           
       }
       // 用户验证
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(appletLoginRest.getOpenid(), "123456"));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(appletLoginRest.getOpenid(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(appletLoginRest.getOpenid(), Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(appletLoginRest.getOpenid(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        String string =  tokenService.createToken(loginUser);
        ajax.put(Constants.TOKEN, string);
        return ajax;
    }
}
